package com.hxzy.tms.action;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;

import com.google.gson.Gson;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.service.UserService;
import com.hxzy.tms.session.SessionHolder;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends AbstractAction {

	public static final String SESSION_KEY="SESSION_KEY";
    private static final long serialVersionUID = -7604563356079928795L;
    private String email;
    private String passwd;
    private UserService userService;
    
    public String index() throws Exception{
        return INPUT;
        
    }
    public String post() throws Exception{
        User user=userService.login(getEmail(), getPasswd(), ServletActionContext.getRequest().getRemoteAddr());
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        ServletActionContext.getResponse().setContentType("application/json");
        if (user != null) {
            ActionContext.getContext().getSession().put("SESSION_KEY", user);
            ServletActionContext.getResponse().getWriter().println("{\"status\":1, \"message\":\"登陆成功\"}");
        }else {
            ServletActionContext.getResponse().getWriter().println("{\"status\":0, \"message\":\"登陆失败\"}");
        }
        return null;
    }
    public String session() throws Exception{
        User user=(User)ActionContext.getContext().getSession().get("SESSION_KEY");
        if (user == null) {
            user = userService.getUser(getCookie("hash"), ipv4()).data;
        }
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        ServletActionContext.getResponse().setContentType("application/json");
        if (user != null) {
            Gson gson=new Gson();
            ServletActionContext.getResponse().getWriter().println(gson.toJson(user));
        } else {
            ServletActionContext.getResponse().getWriter().println("{}");
        }
        return null;
    }
    public String invalide() throws Exception {
        ((SessionMap<String, Object>) ActionContext.getContext().getSession()).invalidate();
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        ServletActionContext.getResponse().setContentType("application/json");
        ServletActionContext.getResponse().getWriter().println("{\"status\":1, \"message\":\"退出成功\"}");
        return null;
    }
    
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    
    
}
